<template>
  <div>
    <el-row>
      <el-col :span="2" :offset="22">
        <el-page-header @back="goBack"> </el-page-header>
      </el-col>
    </el-row>
    <el-row style="margin: 15px 0">
      <el-alert
        title="添加商品信息"
        type="info"
        :closable="false"
        center
        show-icon
      >
      </el-alert>
    </el-row>
    <el-steps
      style="margin: 20px 50px"
      size="mini"
      align-center
      :active="active * 1"
      finish-status="success"
    >
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <el-form ref="addFormRef" :rules="rules" :model="addform">
      <el-tabs
        :before-leave="beforeTabLeave"
        v-model="active"
        tab-position="left"
        @tab-click="handleClick"
      >
        <el-tab-pane name="0" label="基本信息">
          <el-form-item prop="goods_name" label="商品名称">
            <el-input
              size="mini"
              clearable
              v-model="addform.goods_name"
              placeholder="请输入商品名称"
            ></el-input>
          </el-form-item>
          <el-form-item prop="goods_price" label="商品价格">
            <el-input
              size="mini"
              clearable
              v-model.number="addform.goods_price"
              placeholder="请输入商品价格"
            ></el-input>
          </el-form-item>
          <el-form-item prop="goods_weight" label="商品重量">
            <el-input
              size="mini"
              clearable
              v-model.number="addform.goods_weight"
              placeholder="请输入商品重量"
            ></el-input>
          </el-form-item>
          <el-form-item prop="goods_number" label="商品数量">
            <el-input
              size="mini"
              clearable
              v-model.number="addform.goods_number"
              placeholder="请输入商品数量"
            ></el-input>
          </el-form-item>
          <el-form-item prop="goods_cat" label="商品分类">
            <el-cascader
              size="mini"
              style="width: 100%"
              v-model="addform.goods_cat"
              :options="options"
              @change="parentCateChanged"
              :props="{
                expandTrigger: 'hover',
                value: 'cat_id',
                label: 'cat_name',
                children: 'children',
                checkStrictly: true,
              }"
            ></el-cascader>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane name="1" label="商品参数">
          <div
            style="margin: 20px 0"
            v-for="item in manyTableData"
            :key="item.attr_id"
          >
            <h4 style="margin: 20px 0">{{ item.attr_name }}</h4>
            <el-checkbox-group v-model="checkMany">
              <el-checkbox
                v-for="item1 in item.attr_vals"
                :key="item1"
                :label="item1"
              ></el-checkbox>
            </el-checkbox-group>
            <hr />
          </div>
        </el-tab-pane>
        <el-tab-pane name="2" label="商品属性">
          <div
            style="margin: 20px 0"
            v-for="item in onlyTableData"
            :key="item.attr_id"
          >
            <h4 style="margin: 20px 0">{{ item.attr_name }}</h4>
            <el-checkbox-group v-model="checkOnly">
              <el-checkbox
                v-for="item1 in item.attr_vals"
                :key="item1"
                :label="item1"
              ></el-checkbox>
            </el-checkbox-group>
            <hr />
          </div>
        </el-tab-pane>
        <el-tab-pane name="3" label="商品图片">
          <el-upload
            :action="uploadURL"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            list-type="picture-card"
            :headers="headersStr"
          >
            <i class="el-icon-plus"></i>
          </el-upload>

          <el-dialog title="图片预览" :visible.sync="picShow" width="30%">
            <img style="width: 100%; height: 100%" :src="picSrc" alt="" />
          </el-dialog>
        </el-tab-pane>
        <el-tab-pane name="4" label="商品内容">
          <quillEditor
            style="height: 300px"
            v-model="addform.goods_introduce"
          ></quillEditor>
          <el-button
            style="margin-top: 90px"
            class="btnAdd"
            type="primary"
            @click="add"
            >添加商品</el-button
          >
        </el-tab-pane>
      </el-tabs>
    </el-form>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import { quillEditor } from 'vue-quill-editor';
import { getCategoriesList } from '../../api/categories';
import { getAttributesList } from '../../api/params';
import { addGoods } from '../../api/goods';

export default {
  components: { quillEditor },
  data() {
    return {
      picShow: false,
      picSrc: null,
      headersStr: {
        Authorization: window.sessionStorage.getItem('token'),
      },
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      active: '0',
      addform: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: [],
      },
      checkMany: [],
      checkOnly: [],
      rules: {
        goods_name: [{ required: true, message: '请输入', trigger: 'blur' }],
        goods_price: [
          { required: true, message: '请输入', trigger: 'blur' },
          { type: 'number', message: '必须为数字值' },
        ],
        goods_weight: [
          { required: true, message: '请输入', trigger: 'blur' },
          { type: 'number', message: '必须为数字值' },
        ],
        goods_number: [
          { required: true, message: '请输入', trigger: 'blur' },
          { type: 'number', message: '必须为数字值' },
        ],
        goods_cat: [
          { required: true, message: '请输入', trigger: 'blur' },
          { type: 'array', message: '必须为数字值' },
        ],
      },
      options: [],
      manyTableData: [], // 动态参数列表
      onlyTableData: [],
    };
  },
  methods: {
    add() {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) {
          return this.$message.error('填写必要的表单项！');
        }
        // 执行添加的业务逻辑
        this.onAdd();
      });
    },
    async onAdd() {
      this.manyTableData.forEach((item) => {
        const newInfo = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(' '),
        };
        this.addform.attrs.push(newInfo);
      });
      // 处理静态属性
      this.onlyTableData.forEach((item) => {
        const newInfo = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals,
        };
        this.addform.attrs.push(newInfo);
      });
      this.addform.goods_cat = this.addform.goods_cat.join(',');
      const res = await addGoods(this.addform);
      if (res.meta.status !== 201) {
        return this.$message.error(res.meta.msg);
      }
      this.$message.success(res.meta.msg);
      this.$router.go(-1);
    },
    // 图片预览
    handlePreview(files) {
      this.picShow = true;
      this.picSrc = files.response.data.url;
    },
    handleRemove(file) {
      // 1. 获取将要删除的图片的临时路径
      const filePath = file.response.data.tmp_path;
      // 2. 从pics数组中，找到这个图片对应的索引值
      const i = this.addform.pics.findIndex((x) => x.pic === filePath);
      // 3. 调用数组的splice方法，把图片信息对象，从pics数组中移除
      this.addform.pics.splice(i, 1);
    },
    // 文件上传成功时
    handleSuccess(response) {
      const info = { pic: response.data.tmp_path };
      this.addform.pics.push(info);
    },
    async handleClick() {
      if (this.active === '1') {
        const params = { sel: 'many' };
        const res = await getAttributesList(this.addform.goods_cat[2], params);
        if (res.meta.status !== 200) {
          return this.$message.error('获取状态参数列表失败！');
        }
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ');
        });
        this.manyTableData = res.data;
      }
      if (this.active === '2') {
        const params = { sel: 'only' };
        const res = await getAttributesList(this.addform.goods_cat[2], params);
        if (res.meta.status !== 200) {
          return this.$message.error('获取状态参数列表失败！');
        }
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ');
        });
        this.onlyTableData = res.data;
      }
    },
    // 页签切换前
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addform.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类！');
        return false;
      }
    },
    parentCateChanged() {
      if (this.addform.goods_cat.length !== 3) {
        this.addform.goods_cat = [];
      }
    },
    goBack() {
      this.$router.go(-1);
    },
    // 获取分类列表
    async getParentList() {
      const params = {
        type: 3,
      };
      const res = await getCategoriesList(params);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.options = res.data;
    },
  },
  created() {
    this.getParentList();
  },
};
</script>

<style lang='less' >
.el-step__title {
  font-size: 12px !important;
}
</style>
